const Usecase = require('../../shared/usecase/Usecase')
const Role = require('../../domain/role/role')
const { RoleCodeExistError } = require('../../domain/role/error')
class CreateRole extends Usecase {
  constructor({ roleRepo, database, currentUser }) {
    super()
    this.roleRepo = roleRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }
  async _validate(entity) {
    await entity.validate()
    const role = await this.roleRepo.findByCode(entity.code)
    if (role) throw new RoleCodeExistError()
  }
  async execute(data) {
    const role = Role.create(data)
    await this._validate(role)
    const transaction = await this.sequelize.transaction()
    try {
      await this.roleRepo.create(role, {
        transaction,
        currentUser: this.currentUser,
      })
      await transaction.commit()
      return role
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = CreateRole
